package org.mysocial.services.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;

import org.mysocial.services.dao.GenericDAO;

public abstract class AbstractGenericDAO<T, ID extends Serializable> implements
    GenericDAO<T, ID>
{
	protected EntityManager entityManager;

	protected Class<T> persistentClass;

	@SuppressWarnings("unchecked")
	public AbstractGenericDAO()
	{
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
		    .getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Override
	public void clear()
	{
		entityManager.clear();
	}

	@Override
	public T findById(ID id)
	{
		return entityManager.find(persistentClass, id);
	}

	@Override
	public void flush()
	{
		entityManager.flush();
	}

	@Override
	public Class<T> getPersistentClass()
	{
		return persistentClass;
	}

	@Override
	public void merge(T entity)
	{
		entityManager.merge(entity);
	}

	@Override
	public T persist(T entity)
	{
		entityManager.persist(entity);

		return entity;
	}

	@Override
	public void remove(T entity)
	{
		entityManager.remove(entity);
	}

	public abstract void setEntityManager(EntityManager entityManager);
}